import React, { useState, useRef } from 'react';
import { Form, Input, Button, Typography, Spin, message, Card, Row, Col, Upload, Divider } from 'antd';
import { CopyOutlined, DownloadOutlined, FileTextOutlined, UploadOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';
import type { InputNumberProps } from 'antd';
import InputNumber from 'antd/es/input-number';
import CommonTour, { TourGuideButton } from '@/components/CommonTour';

const { Title, Paragraph } = Typography;
const { TextArea } = Input;

// 定义上传文件类型
interface UploadFile {
  uid: string;
  name: string;
  status?: string;
  response?: any;
  error?: any;
}

/**
 * 文章摘要生成功能
 * 为文章内容生成简洁明了的摘要
 */
const ProseSummaryPage: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [summary, setSummary] = useState<string>('');
  const [summaryLength, setSummaryLength] = useState<number>(200);
  const [uploadedFile, setUploadedFile] = useState<UploadFile | null>(null);
  const [tourVisible, setTourVisible] = useState<boolean>(false);

  // 创建ref引用
  const articleContentRef = useRef<HTMLDivElement>(null);
  const fileUploadRef = useRef<HTMLDivElement>(null);
  const summaryLengthRef = useRef<HTMLDivElement>(null);
  const generateButtonRef = useRef<HTMLDivElement>(null);
  const summaryResultRef = useRef<HTMLDivElement>(null);

  // 组织ref引用
  const tourRefs = {
    articleContent: articleContentRef,
    fileUpload: fileUploadRef,
    summaryLength: summaryLengthRef,
    generateButton: generateButtonRef,
    summaryResult: summaryResultRef
  };

  // 定义steps配置
  const tourSteps = [
    {
      key: 'articleContent',
      title: '输入文章内容',
      description: '请输入需要生成摘要的文章内容',
    },
    {
      key: 'fileUpload',
      title: '上传文章文件',
      description: '也可以通过上传文件的方式提供文章内容',
    },
    {
      key: 'summaryLength',
      title: '设置摘要长度',
      description: '调整摘要的字符数，范围在50-1000之间',
    },
    {
      key: 'generateButton',
      title: '生成摘要',
      description: '点击此按钮开始AI摘要生成过程',
    },
    {
      key: 'summaryResult',
      title: '查看摘要结果',
      description: '生成完成后，您可以在此处查看、复制或下载摘要',
    },
  ];

  // 显示引导
  const showTour = () => {
    // 延迟显示，确保DOM已经渲染
    setTimeout(() => {
      setTourVisible(true);
    }, 100);
  };

  // 处理摘要长度变化
  const handleSummaryLengthChange = (value?: any) => {
    if (value !== undefined) {
      setSummaryLength(value);
    }
  };

  // 处理表单提交，生成摘要
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      const articleContent = values.articleContent || '';

      if (!articleContent.trim() && !uploadedFile) {
        message.warning('请输入文章内容或上传文章文件');
        return;
      }

      setLoading(true);
      setSummary('');

      // 模拟API调用延迟
      setTimeout(() => {
        const generatedSummary = generateSummary(articleContent, summaryLength);
        setSummary(generatedSummary);
        setLoading(false);
        message.success('摘要生成成功！');
      }, 2000);
    } catch (error) {
      setLoading(false);
      message.error('摘要生成失败，请重试');
    }
  };

  // 上传文件配置
  const uploadProps: UploadProps = {
    name: 'file',
    accept: '.txt,.doc,.docx,.pdf',
    beforeUpload: (file) => {
      // 这里模拟文件上传，实际应用中应该调用文件上传API
      const mockFile: UploadFile = {
        uid: `mock-${Date.now()}`,
        name: file.name,
        status: 'done',
      };
      setUploadedFile(mockFile);
      message.success(`${file.name} 文件上传成功`);

      // 返回false阻止默认上传行为
      return false;
    },
    onRemove: () => {
      setUploadedFile(null);
      return true;
    },
    showUploadList: false,
  };

  // 复制摘要内容
  const handleCopySummary = () => {
    if (!summary) {
      message.warning('没有可复制的摘要内容');
      return;
    }

    navigator.clipboard.writeText(summary).then(() => {
      message.success('摘要内容已复制到剪贴板');
    }).catch(() => {
      message.error('复制失败，请手动复制');
    });
  };

  // 下载摘要内容
  const handleDownloadSummary = () => {
    if (!summary) {
      message.warning('没有可下载的摘要内容');
      return;
    }

    const blob = new Blob([summary], { type: 'text/plain;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = '文章摘要.txt';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    message.success('摘要内容已下载');
  };

  // 生成摘要的模拟函数
  const generateSummary = (content: string, length: number): string => {
    // 这里是模拟生成摘要的逻辑，实际应用中应该调用AI模型

    // 如果有上传的文件，模拟从文件中提取内容生成摘要
    if (uploadedFile && !content.trim()) {
      return `这是根据上传的文件《${uploadedFile.name}》生成的摘要。文件内容主要讨论了相关领域的最新发展和趋势，分析了当前面临的主要挑战和机遇，并提出了一系列具有前瞻性的建议和解决方案。通过对文件内容的系统梳理，我们可以看出作者对该领域有着深入的了解和独到的见解。`;
    }

    // 从文章内容中提取关键词和关键句
    let keywords: string[] = [];
    const sentences = content.split(/[。！？]/);

    // 简单的关键词提取逻辑
    const keywordRegex = /研究|发现|分析|重要|关键|建议|问题|解决方案|发展|趋势/g;
    let match;
    while ((match = keywordRegex.exec(content)) !== null) {
      if (!keywords.includes(match[0])) {
        keywords.push(match[0]);
      }
    }

    // 如果没有找到足够的关键词，使用默认关键词
    if (keywords.length === 0) {
      keywords = ['研究', '分析', '发展'];
    }

    // 选择出现关键词最多的句子作为摘要组成部分
    const keySentences = sentences
      .filter(sentence => sentence.trim())
      .sort((a, b) => {
        const aCount = keywords.filter(keyword => a.includes(keyword)).length;
        const bCount = keywords.filter(keyword => b.includes(keyword)).length;
        return bCount - aCount;
      })
      .slice(0, 3);

    // 生成摘要
    let generatedSummary = keySentences.join('。') + '。';

    // 根据指定的长度调整摘要
    if (generatedSummary.length > length) {
      generatedSummary = generatedSummary.substring(0, length) + '...';
    }

    return generatedSummary;
  };

  return (
    <>
      <div style={{ padding: '24px' }}>
        <Typography>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <Title level={1}>文章摘要<TourGuideButton onClick={showTour} /></Title>
          </div>
          <Paragraph>
            输入文章内容或上传文章文件，AI将为您生成简洁明了的摘要。
          </Paragraph>
        </Typography>

        <Row gutter={[16, 16]}>
          <Col xs={24} md={12}>
            <Card title="文章输入与设置" size="small">
              <Form
                form={form}
                layout="vertical"
              >
                <Form.Item
                  label="文章内容"
                  name="articleContent"
                >
                  <div ref={articleContentRef}>
                    <TextArea
                      rows={10}
                      placeholder="请输入文章内容，或上传文章文件"
                      maxLength={10000}
                      showCount
                    />
                  </div>
                </Form.Item>

                <Form.Item>
                  <div ref={fileUploadRef} style={{ marginBottom: '16px' }}>
                    <Upload {...uploadProps}>
                      <Button icon={<UploadOutlined />}>上传文章文件</Button>
                    </Upload>
                    {uploadedFile && (
                      <div style={{ marginTop: '8px', display: 'flex', alignItems: 'center', color: '#52c41a' }}>
                        <FileTextOutlined style={{ marginRight: '4px' }} />
                        {uploadedFile.name}
                      </div>
                    )}
                  </div>
                </Form.Item>

                <Divider style={{ margin: '16px 0' }} />

                <Form.Item
                  label="摘要长度（字符数）"
                  name="summaryLength"
                >
                  <div ref={summaryLengthRef}>
                    <InputNumber
                      min={50}
                      max={1000}
                      defaultValue={200}
                      onChange={handleSummaryLengthChange}
                      style={{ width: '100%' }}
                    />
                  </div>
                </Form.Item>

                <Form.Item>
                  <div ref={generateButtonRef}>
                    <Button
                      type="primary"
                      onClick={handleSubmit}
                      loading={loading}
                      block
                    >
                      {loading ? '生成中...' : '生成摘要'}
                    </Button>
                  </div>
                </Form.Item>
              </Form>
            </Card>
          </Col>

          <Col xs={24} md={12}>
            <Card title="摘要结果" size="small" ref={summaryResultRef}>
              {loading ? (
                <div style={{ textAlign: 'center', padding: '60px 0' }}>
                  <Spin size="large" />
                  <p style={{ marginTop: '16px' }}>正在生成文章摘要，请稍候...</p>
                </div>
              ) : summary ? (
                <div>
                  <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: '16px' }}>
                    <Button
                      type="primary"
                      icon={<CopyOutlined />}
                      onClick={handleCopySummary}
                      style={{ marginRight: '8px' }}
                    >
                      复制摘要
                    </Button>
                    <Button
                      icon={<DownloadOutlined />}
                      onClick={handleDownloadSummary}
                    >
                      下载摘要
                    </Button>
                  </div>
                  <TextArea
                    value={summary}
                    rows={18}
                    readOnly
                    style={{ backgroundColor: '#fafafa' }}
                  />
                </div>
              ) : (
                <div style={{ textAlign: 'center', padding: '60px 0', color: '#999' }}>
                  摘要结果将显示在这里
                </div>
              )}
            </Card>
          </Col>
        </Row>
      </div>

      <CommonTour
        open={tourVisible}
        onClose={() => setTourVisible(false)}
        steps={tourSteps}
        targetRefs={tourRefs}
      />
    </>
  );
};

export default ProseSummaryPage;